import axios from 'axios';
import { ElNotification, ElMessageBox } from 'element-plus';
import { getToken } from '@/utils/auth';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
// 创建axios实例
const baseURL = process.env.NODE_ENV === 'development' ? '/api' : '';
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL,
  // 超时
  timeout: 10000,
});

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

// request拦截器
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['PAY-Token'] = getToken('PAY-Token'); // 让每个请求携带自定义token 请根据实际情况自行修改
      config.headers['PAY-UserId'] = getToken('PAY-UserId'); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.cancelToken = source.token;
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  res => {
    const code = res.data.excCode;
    if (code !== 10000) {
      if (code === 10104) {
        ElMessageBox.confirm('登录过期，请重新登录！', '确定登出', {
          confirmButtonText: '重新登录',
          showCancelButton: false,
          type: 'warning',
        }).then(() => {});
        source.cancel(); // 取消请求
      } else {
        ElNotification.error({
          title: res.data.message,
        });
        return Promise.reject('error');
      }
    } else {
      return res.data.data;
    }
  },
  error => {
    return Promise.reject(error);
  }
);

export default service;
